package com.aaie.gru.position.controller;


import com.aaie.gru.config.NoRepeatSubmit;
import com.aaie.gru.getui.PushtoSingle;
import com.aaie.gru.gruenum.UserType;
import com.aaie.gru.login.entity.LoginUser;
import com.aaie.gru.position.entity.GruSysPosition;
import com.aaie.gru.position.entity.GruSysPositionGet;
import com.aaie.gru.position.entity.GruSysPositionGetDto;
import com.aaie.gru.position.entity.GruSysPositionGetVo;
import com.aaie.gru.position.service.IGruSysPositionGetService;
import com.aaie.gru.position.service.IGruSysPositionService;
import com.aaie.gru.response.ResMessage;
import com.aaie.gru.user.entity.GruSysUser;
import com.aaie.gru.user.service.IGruSysUserService;
import com.aaie.gru.util.CommonUtil;
import com.aaie.gru.util.ExceptionEnums;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 获取指定用户登录地理位置 前端控制器
 * </p>
 *
 * @author lvxing
 * @since 2019-09-13
 */
@Api(tags = "登录用户位置模块--获取的固定用户位置")
@RestController
@RequestMapping("/position")
public class GruSysPositionGetController {

    @Autowired
    IGruSysPositionGetService gruSysPositionGetService;

    @Autowired
    IGruSysPositionService gruSysPositionService;

    @Autowired
    IGruSysUserService gruSysUserService;

    /**
     * 添加获取地理位置信息
     *
     * @param session
     * @param stuId   学生id
     * @return
     */
    @ApiOperation(value = "添加获取地理位置信息", notes = "添加获取地理位置信息")
    @PostMapping("/addPositionGet")
    @NoRepeatSubmit
    public String addPositionGet(HttpSession session, String stuId) {
        LoginUser user = CommonUtil.getUser(session);
        if (user == null) {
            return ResMessage.error(ExceptionEnums.LOGINUSER_IS_NULL.getEmsg(), ExceptionEnums.LOGINUSER_IS_NULL.getEcode());
        }
        GruSysUser gruSysUser = gruSysUserService.getById(stuId);
        QueryWrapper<GruSysPositionGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("originator_id", user.getUserId());
        //queryWrapper.eq("target_id", stuId);
        queryWrapper.eq("position_get_status", "0");
        int count = gruSysPositionGetService.count(queryWrapper);
        if (count > 0) {
            return ResMessage.error("不能同时获取多个学生的地理位置信息", 200);
        }
        String userType = user.getUserType();
        String positionGetNature = "";
        if (userType.equals(UserType.GUARDIAN.getValue())) {
            positionGetNature = "0";
        } else if (userType.equals(UserType.PARENT.getValue())) {
            positionGetNature = "1";
        }
        String userId = user.getUserId();
        GruSysPositionGet gruSysPositionGet = new GruSysPositionGet();
        try {
            // 发起人一定是当前登录用户 有可能是家长 也可能是监护人
            gruSysPositionGet.setOriginatorId(userId);
            // 目标一定是学生
            gruSysPositionGet.setTargetId(stuId);
            // 真正的授权人就不一定了 要看传进来的positionGetNature 如果是0 则是监护人获取，家长授权，如果是1 则是家长获取，监护人授权
            String stuGurdianId = gruSysUser.getStuGurdianId();
            String stuFatherId = gruSysUser.getStuFatherId();
            String stuMotherId = gruSysUser.getStuMotherId();
            String authorizationId = "";
            // 监护人发起
            if (StringUtils.equals("0", positionGetNature)) {
                if (StringUtils.isNotEmpty(stuFatherId) && StringUtils.isNotEmpty(stuMotherId)) {
                    authorizationId = stuFatherId + "," + stuMotherId;
                } else if (StringUtils.isNotEmpty(stuFatherId)) {
                    authorizationId = stuFatherId;
                } else if (StringUtils.isNotEmpty(stuMotherId)) {
                    authorizationId = stuMotherId;
                }
            } else if (StringUtils.equals("1", positionGetNature)) {
                // 家长发起
                authorizationId = stuGurdianId;
            }
            if (StringUtils.isEmpty(authorizationId)) {
                return ResMessage.error("未获取到授权人信息", 200);
            }
            gruSysPositionGet.setAuthorizationId(authorizationId);
            // 0是刚创建状态
            gruSysPositionGet.setPositionGetStatus("0");
            gruSysPositionGet.setPositionGetNature(positionGetNature);

            String updateTime = CommonUtil.generateLocalDateTime();
            long updateTimeSort = CommonUtil.generateCurrentTimeMillis();
            String userName = CommonUtil.getUser(session).getUserName();
            gruSysPositionGet.setCreateName(userName);
            gruSysPositionGet.setCreateTime(updateTime);
            gruSysPositionGet.setCreateTimeSort(updateTimeSort);
            gruSysPositionGet.setUpdateName(userName);
            gruSysPositionGet.setUpdateTime(updateTime);
            gruSysPositionGet.setUpdateTimeSort(updateTimeSort);
            gruSysPositionGetService.save(gruSysPositionGet);
            // 给授权人推送消息
            String[] pushIdArr = authorizationId.split(",");
            if (pushIdArr != null && pushIdArr.length > 0) {
                GruSysUser targetUser = gruSysUserService.getById(stuId);
                for (String pushId : pushIdArr) {
                    GruSysUser gruSysUser1 = gruSysUserService.getById(pushId);
                    String userClientId = gruSysUser1.getUserClientId();
                    String platform = gruSysUser1.getPlatform();
                    if (StringUtils.isNotEmpty(userClientId)) {
                        PushtoSingle.pushtoSingle("授权位置信息", user.getUserName() + "想获取" + targetUser.getUserName() + "的位置信息，请点击地理位置授权", "{\"bizType\":\"100\"}", userClientId, platform);
                    }
                }
            }
            return ResMessage.ok(gruSysPositionGet);
        } catch (Exception e) {
            //e.printStackTrace();
            return ResMessage.error("/addPositionGet/addPositionGet报错", 500);
        }
    }

    /**
     * 授权人同意或拒绝
     * 这个接口先考虑直接更新所有授权人是当前登录人的数据
     *
     * @param session
     * @return
     */
    @ApiOperation(value = "授权人同意或拒绝", notes = "授权人同意或拒绝")
    @PostMapping("/editPositionGet")
    public String editPositionGet(HttpSession session, @RequestBody GruSysPositionGet gruSysPositionGet) {
        try {
            LoginUser user = CommonUtil.getUser(session);
            if (user == null) {
                return ResMessage.error(ExceptionEnums.LOGINUSER_IS_NULL.getEmsg(), ExceptionEnums.LOGINUSER_IS_NULL.getEcode());
            }
            // 检验发起人取消获取位置
            GruSysPositionGet param = gruSysPositionGetService.getById(gruSysPositionGet.getId());
            if (param == null) {
                return ResMessage.error("发起人已经取消了授权", 200);
            }
            // 授权人同意
            String positionGetStatus = gruSysPositionGet.getPositionGetStatus();
            gruSysPositionGet.setPositionGetStatus(positionGetStatus);
            String targetId = gruSysPositionGet.getTargetId();
            String originatorId = gruSysPositionGet.getOriginatorId();
            GruSysUser targetUser = gruSysUserService.getById(targetId);
            GruSysUser originatorUser = gruSysUserService.getById(originatorId);
            if (StringUtils.isNotEmpty(originatorUser.getUserClientId())) {
                if ("1".equals(positionGetStatus)) {
                    // 授权完给监护人推送消息
                    PushtoSingle.pushtoSingle("同意授权", user.getUserName() + "同意您获取" + targetUser.getUserName() + "的地理位置", "{\"bizType\":\"300\"}", originatorUser.getUserClientId(), originatorUser.getPlatform());
                } else if ("2".equals(positionGetStatus)) {
                    PushtoSingle.pushtoSingle("拒绝授权", user.getUserName() + "拒绝您获取" + targetUser.getUserName() + "的地理位置", "{\"bizType\":\"400\"}", originatorUser.getUserClientId(), originatorUser.getPlatform());
                }
            }
            String updateTime = CommonUtil.generateLocalDateTime();
            long updateTimeSort = CommonUtil.generateCurrentTimeMillis();
            String userName = CommonUtil.getUser(session).getUserName();
            gruSysPositionGet.setUpdateName(userName);
            gruSysPositionGet.setUpdateTime(updateTime);
            gruSysPositionGet.setUpdateTimeSort(updateTimeSort);
            gruSysPositionGetService.saveOrUpdate(gruSysPositionGet);
            return ResMessage.ok(gruSysPositionGet);
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessage.error("授权失败", 500);
        }

    }

    /**
     * 获取人查看获取位置进度
     *
     * @param session
     * @return
     */
    @ApiOperation(value = "获取人查看获取位置进度", notes = "获取人查看获取位置进度")
    @PostMapping("/getPositionGetByOri")
    public String getPositionGetByOri(HttpSession session, @RequestBody List<String> ids) {
        LoginUser user = CommonUtil.getUser(session);
        if (user == null) {
            return ResMessage.error(ExceptionEnums.LOGINUSER_IS_NULL.getEmsg(), ExceptionEnums.LOGINUSER_IS_NULL.getEcode());
        }
        String userId = user.getUserId();
        QueryWrapper<GruSysPositionGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("originator_id", userId);
        if (!CollectionUtils.isEmpty(ids)) {
            queryWrapper.in("target_id", ids);
        }
        queryWrapper.orderByDesc("update_time_sort");
        List<GruSysPositionGet> list = gruSysPositionGetService.list(queryWrapper);
        List<GruSysPositionGetVo> gruSysPositionGetVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (GruSysPositionGet gruSysPositionGet : list) {
                GruSysPositionGetVo gruSysPositionGetVo = new GruSysPositionGetVo();
                BeanUtils.copyProperties(gruSysPositionGet, gruSysPositionGetVo);
                String targetId = gruSysPositionGet.getTargetId();
                GruSysUser gruSysUser = gruSysUserService.getById(targetId);
                String userName = gruSysUser.getUserName();
                gruSysPositionGetVo.setUserName(userName);
                gruSysPositionGetVoList.add(gruSysPositionGetVo);
                if ("0".equals(gruSysPositionGet.getPositionGetStatus()) || "2".equals(gruSysPositionGet.getPositionGetStatus())) {
                    continue;
                }
                GruSysPosition gruSysPosition = gruSysPositionService.getById(targetId);
                gruSysPositionGetVo.setGruSysPosition(gruSysPosition);
            }
        }
        return ResMessage.ok(gruSysPositionGetVoList);
    }

    /**
     * 删除获取地理位置
     * @param gruSysPositionGetDto
     * @return
     */
    @ApiOperation(value = "删除获取地理位置", notes = "删除获取地理位置")
    @PostMapping("/delPositionGet")
    public String delPositionGet(@RequestBody GruSysPositionGetDto gruSysPositionGetDto) {
        boolean b = gruSysPositionGetService.removeById(gruSysPositionGetDto.getId());
        if ("0".equals(gruSysPositionGetDto.getCancelType())) {
            // 获取授权人信息
            String authorizationId = gruSysPositionGetDto.getAuthorizationId();
            if (StringUtils.isNotEmpty(authorizationId)) {
                String[] authorizationIdArr = authorizationId.split(",");
                if (authorizationIdArr != null && authorizationIdArr.length > 0) {
                    String targetId = gruSysPositionGetDto.getTargetId();
                    GruSysUser targetUser = gruSysUserService.getById(targetId);
                    for (String authorizationIdStr : authorizationIdArr) {
                        GruSysUser gruSysUser = gruSysUserService.getById(authorizationIdStr);
                        if (StringUtils.isNotEmpty(gruSysUser.getUserClientId())) {
                            PushtoSingle.pushtoSingle("取消授权", gruSysUser.getUserName() + "取消获取您孩子" + targetUser.getUserName() + "的位置信息", "{\"bizType\":\"500\"}", gruSysUser.getUserClientId(), gruSysUser.getPlatform());
                        }
                    }
                }
            }
        }
        if (b) {
            return ResMessage.ok(gruSysPositionGetDto);
        } else {
            return ResMessage.error("清除获取位置消息失败", 200);
        }
    }

    /**
     * 授权人查看授权信息
     *
     * @param session
     * @return
     */
    @ApiOperation(value = "授权人查看授权信息", notes = "授权人查看授权信息")
    @PostMapping("/getPositionGetByAuth")
    public String getPositionGetByAuth(HttpSession session) {
        LoginUser user = CommonUtil.getUser(session);
        if (user == null) {
            return ResMessage.error(ExceptionEnums.LOGINUSER_IS_NULL.getEmsg(), ExceptionEnums.LOGINUSER_IS_NULL.getEcode());
        }
        String userId = user.getUserId();
        QueryWrapper<GruSysPositionGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("authorization_id", userId);
        queryWrapper.eq("position_get_status", "0");
        queryWrapper.orderByDesc("update_time_sort");
        List<GruSysPositionGet> gruSysPositionGetList = gruSysPositionGetService.list(queryWrapper);
        List<GruSysPositionGetVo> gruSysPositionGetVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(gruSysPositionGetList)) {
            for (GruSysPositionGet gruSysPositionGet : gruSysPositionGetList) {
                GruSysPositionGetVo gruSysPositionGetVo = new GruSysPositionGetVo();
                BeanUtils.copyProperties(gruSysPositionGet, gruSysPositionGetVo);
                String targetId = gruSysPositionGet.getTargetId();
                GruSysUser gruSysUser = gruSysUserService.getById(targetId);
                String userName = gruSysUser.getUserName();
                gruSysPositionGetVo.setUserName(userName);
                gruSysPositionGetVoList.add(gruSysPositionGetVo);
            }
        }
        return ResMessage.ok(gruSysPositionGetVoList);
    }

    @ApiOperation(value = "删除批量获取地理位置", notes = "删除批量获取地理位置")
    @PostMapping("/delBatchPositionGet")
    public String delPositionGet(@RequestBody List<GruSysPositionGet> gruSysPositionGetList, HttpSession session) {
        LoginUser user = CommonUtil.getUser(session);
        if (user == null) {
            return ResMessage.error(ExceptionEnums.LOGINUSER_IS_NULL.getEmsg(), ExceptionEnums.LOGINUSER_IS_NULL.getEcode());
        }
        if (CollectionUtils.isEmpty(gruSysPositionGetList)) {
            return ResMessage.error("参数不能为空", 200);
        }
        List<GruSysPositionGetVo> gruSysPositionGetVoList = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        for (GruSysPositionGet gruSysPositionGet : gruSysPositionGetList) {
            String positionGetStatus = gruSysPositionGet.getPositionGetStatus();
            if (!StringUtils.equals("0",positionGetStatus)) {
                ids.add(gruSysPositionGet.getId());
            }
            GruSysPositionGetVo gruSysPositionGetVo = new GruSysPositionGetVo();
            BeanUtils.copyProperties(gruSysPositionGet, gruSysPositionGetVo);
            String targetId = gruSysPositionGet.getTargetId();
            GruSysUser gruSysUser = gruSysUserService.getById(targetId);
            String userName = gruSysUser.getUserName();
            gruSysPositionGetVo.setUserName(userName);
            gruSysPositionGetVoList.add(gruSysPositionGetVo);
            if ("0".equals(gruSysPositionGet.getPositionGetStatus()) || "2".equals(gruSysPositionGet.getPositionGetStatus())) {
                continue;
            }
            GruSysPosition gruSysPosition = gruSysPositionService.getById(targetId);
            gruSysPositionGetVo.setGruSysPosition(gruSysPosition);
        }
        if (!CollectionUtils.isEmpty(ids)) {
            gruSysPositionGetService.removeByIds(ids);
        }
        return ResMessage.ok(gruSysPositionGetVoList);
    }
}
